
package com.lmx.persistence.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.DicttypeTenant;
import com.lmx.repoDomain.tmodel.Privilege;
import com.lmx.repoDomain.tmodel.Role;
import com.lmx.repoDomain.tmodel.Tenant;
import com.lmx.repoDomain.tmodel.TenantPrivilege;
import com.lmx.repoDomain.tmodel.TradeAccount;
import com.lmx.repoDomain.tmodel.TypegroupTenant;
import com.lmx.repoDomain.tmodel.business.Organization;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati

/**
 * 
 * 
 * @author huibati
 * @version 1.00
 */
@Service
@Scope("prototype")
public class TenantService<T> {

	private Log logger = LogFactory.getLog(this.getClass());

	@PersistenceContext
	private EntityManager em;

	@Autowired
	private GenericService dslJpaService;

	@Autowired
	private CommonService commonService;
	@Autowired
	private TenantPrivilegeService tenantPrivilegeService;
	@Autowired
	private DicttypeService dicttypeService;

	/**
	 * 获取
	 */
	public Tenant getTenantById(Long id) {
		StringBuilder query = new StringBuilder("select c from Tenant c where c.id = ?1 ");
		Tenant ct = (Tenant) this.em.createQuery(query.toString()).setParameter(1, id).getSingleResult();
		return ct;
	}

	/**
	 * 产生新的管理员// 并修改org admin
	 */
	public void createAdminUserByTenant(Tenant tenant, Role role, Organization org) {
		User admin = new User();
		admin.setDelStatus((short) 0);
		admin.setTenant(tenant);
		admin.setOrg(org);
		admin.setRole(role);
		admin.setName(tenant.getLinkMan());
		admin.setLoginName(tenant.getLinkManTel());
		admin.setPasscode(CommonUtil.stringMD5(tenant.getLinkManTel()));
		admin.setAppPassWord(CommonUtil.stringMD5(tenant.getLinkManTel()));
		admin.setStaffTel(tenant.getLinkManTel());
		admin.setStaffStatus(commonService.getDicttype(CommonConstants.DICTTYPE.EMPLOYEE_STATUS_1.label()));
		dslJpaService.setEntityClass(User.class);
		dslJpaService.create(admin);
		org.setAdmin(admin);
		dslJpaService.setEntityClass(Organization.class);
		dslJpaService.create(org);

	}

	/**
	 * 产生新的角色 管理员角色 以及公众号角色 手机角色
	 */
	@Transactional
	public Role createRoleByTenant(Tenant tenant) {
		Role wechatRole = new Role();
		wechatRole.setTenant(tenant);
		wechatRole.setCode("wechat");
		wechatRole.setName("公众号角色");
		wechatRole.setRemark("系统自动生成");
		wechatRole.setDelStatus((short) 0);
		StringBuilder query = new StringBuilder("select c from Privilege c where c.delStatus != ?1  and c.type = ?2");
		List<Privilege> wechatPrivileges = this.em.createQuery(query.toString()).setParameter(1, (short) 1)
				.setParameter(2, 21).getResultList();
		wechatRole.setPrivileges(wechatPrivileges);
		dslJpaService.setEntityClass(Role.class);
		dslJpaService.create(wechatRole);

		Role appRole = new Role();
		appRole.setTenant(tenant);
		appRole.setCode("app");
		appRole.setName("app角色");
		appRole.setRemark("系统自动生成");
		appRole.setDelStatus((short) 0);
		query.delete(0, query.length());
		query.append("select c from Privilege c where c.delStatus != ?1  and c.type = ?2");
		List<Privilege> appPrivileges = this.em.createQuery(query.toString()).setParameter(1, (short) 1)
				.setParameter(2, 11).getResultList();
		appRole.setPrivileges(appPrivileges);
		dslJpaService.setEntityClass(Role.class);
		dslJpaService.create(appRole);

		Role adminRole = new Role();
		adminRole.setTenant(tenant);
		adminRole.setName("管理员");
		adminRole.setCode("admin");
		adminRole.setRemark("系统自动生成");
		adminRole.setType(2);
		adminRole.setDelStatus((short) 0);
		// 初始化权限信息 huibati
		query.delete(0, query.length());
		query.append("select c from TenantPrivilege c where c.delStatus != ?2 and c.tenant.id = ?1");
		List<TenantPrivilege> privilegesT = this.em.createQuery(query.toString()).setParameter(1, tenant.getId())
				.setParameter(2, (short) 1).getResultList();
		List<Privilege> privileges = new ArrayList<>();
		for (TenantPrivilege data : privilegesT) {
			privileges.add(data.getPrivilege());
		}
		adminRole.setPrivileges(privileges);
		dslJpaService.setEntityClass(Role.class);
		adminRole = (Role) dslJpaService.create(adminRole);
		return adminRole;
	}

	/**
	 * 产生新的org
	 */
	public Organization createOrgByTenant(Tenant tenant) {
		Organization org = new Organization();
		org.setTenant(tenant);
		// 初始化其它org信息 huibati
		org.setDelStatus((short) 0);
		org.setOrgName(tenant.getOrgName());
		org.setOrgShortName(tenant.getOrgShortName());
		org.setOrgCode(tenant.getOrgCode());
		org.setAddress(tenant.getAddress());
		org.setOrgTel(tenant.getOrgTel());
		org.setLegalPerson(tenant.getLegalPerson());
		org.setLicenseImg(tenant.getLicenseImg());
		org.setRemark(tenant.getRemark());
		org.setLinkMan(tenant.getLinkMan());
		org.setLinkManTel(tenant.getLinkManTel());
		org.setLinkManQQ(tenant.getLinkManQQ());
		org.setLinkManMail(tenant.getLinkManMail());
		dslJpaService.setEntityClass(Organization.class);
		org = (Organization) dslJpaService.create(org);
		return org;
	}

	/**
	 * 产生org所对应的账户
	 */
	public TradeAccount createOrgAccount(Organization org) {
		TradeAccount account = new TradeAccount();
		account.setOrg(org);
		// 初始化其它org信息 huibati
		account.setBalance(0.0);
		account.setTenant(org.getTenant());
		account.setDelStatus((short) 0);
		dslJpaService.setEntityClass(TradeAccount.class);
		account = (TradeAccount) dslJpaService.create(account);
		return account;
	}

	/**
	 * 修改org
	 */
	@Transactional
	public void updateOrgByTenant(Tenant tenant) {
		Organization org = null;
		StringBuilder query = new StringBuilder("select c from Organization c where c.tenant.id = ?1");
		List resultList = this.em.createQuery(query.toString()).setParameter(1, tenant.getId()).getResultList();
		if (resultList.size() > 0) {
			org = (Organization) resultList.get(0);
		}
		if (org == null) {

		} else {
			org.setOrgName(tenant.getOrgName());
			org.setOrgShortName(tenant.getOrgShortName());
			org.setOrgCode(tenant.getOrgCode());
			org.setAddress(tenant.getAddress());
			org.setOrgTel(tenant.getOrgTel());
			org.setLegalPerson(tenant.getLegalPerson());
			org.setLicenseImg(tenant.getLicenseImg());
			org.setRemark(tenant.getRemark());
			org.setLinkMan(tenant.getLinkMan());
			org.setLinkManTel(tenant.getLinkManTel());
			org.setLinkManQQ(tenant.getLinkManQQ());
			org.setLinkManMail(tenant.getLinkManMail());
			dslJpaService.setEntityClass(Organization.class);
			dslJpaService.update(org);
		}
	}

	/**
	 * 修改租户权限
	 * 
	 * @author ytche
	 * @param tenant
	 * @param privilegeMap
	 * @date 2017年6月5日 上午11:47:08
	 */
	@Transactional
	public void updatePrivilege(Tenant tenant, Map<String, List<Object>> privilegeMap) {
		if (privilegeMap == null || !privilegeMap.containsKey("privileges")) {
			return;
		}
		tenantPrivilegeService.deleteByTenantId(tenant.getId());
		List<Object> privileges = privilegeMap.get("privileges");
		for (Object object : privileges) {
			TenantPrivilege tenantPrivilege = (TenantPrivilege) object;
			tenantPrivilege.setTenant(tenant);
			this.tenantPrivilegeService.create(tenantPrivilege);
		}
		privilegeMap.remove("privileges");
	}

	/**
	 * 
	 */
	@Transactional
	public void deleteTenantPrivilege(Long tenantId) {
		if (tenantId != null) {
			StringBuilder query = new StringBuilder("delete from TenantPrivilege rp where rp.tenant.id = ?1");
			this.em.createQuery(query.toString()).setParameter(1, tenantId).executeUpdate();
		}
	}

	// 生成租户 字典表 数据
	public void createTenantDicttype(Tenant tenant) {
		List dataList = new ArrayList<>();
		TypegroupTenant bedGroup = commonService.getTenantTypeGroup("bedType");
		DicttypeTenant bed1 = new DicttypeTenant();
		bed1.setTenant(tenant);
		bed1.setTypename("高级床位");
		bed1.setCreateDateTime(CommonUtil.getCurrTimes());
		bed1.setTypegroupTenant(bedGroup);
		DicttypeTenant bed2 = new DicttypeTenant();
		bed2.setTenant(tenant);
		bed1.setTypename("普通床位");
		bed2.setCreateDateTime(CommonUtil.getCurrTimes());
		bed2.setTypegroupTenant(bedGroup);
		dataList.add(bed1);
		dataList.add(bed2);
		TypegroupTenant roomGroup = commonService.getTenantTypeGroup("roomType");
		DicttypeTenant room1 = new DicttypeTenant();
		room1.setTenant(tenant);
		room1.setTypename("单人间");
		room1.setCreateDateTime(CommonUtil.getCurrTimes());
		room1.setTypegroupTenant(roomGroup);
		DicttypeTenant room2 = new DicttypeTenant();
		room2.setTenant(tenant);
		room2.setTypename("双人间");
		room2.setCreateDateTime(CommonUtil.getCurrTimes());
		room2.setTypegroupTenant(roomGroup);
		DicttypeTenant room3 = new DicttypeTenant();
		room3.setTenant(tenant);
		room3.setTypename("VIP间");
		room3.setCreateDateTime(CommonUtil.getCurrTimes());
		room3.setTypegroupTenant(roomGroup);
		dataList.add(room1);
		dataList.add(room2);
		dataList.add(room3);
		TypegroupTenant publicGroup = commonService.getTenantTypeGroup("publicType");
		DicttypeTenant public1 = new DicttypeTenant();
		public1.setTenant(tenant);
		public1.setTypename("厕所");
		public1.setCreateDateTime(CommonUtil.getCurrTimes());
		public1.setTypegroupTenant(publicGroup);
		DicttypeTenant public2 = new DicttypeTenant();
		public2.setTenant(tenant);
		public2.setTypename("阳台");
		public2.setCreateDateTime(CommonUtil.getCurrTimes());
		public2.setTypegroupTenant(publicGroup);
		DicttypeTenant public3 = new DicttypeTenant();
		public3.setTenant(tenant);
		public3.setTypename("花园");
		public3.setCreateDateTime(CommonUtil.getCurrTimes());
		public3.setTypegroupTenant(publicGroup);
		dataList.add(public1);
		dataList.add(public2);
		commonService.batchInsert(dataList);
	}

	// 租户由未发布 改为发布
	// @Transactional
	public void operateTenantReleased(Tenant tenant) {
		Organization org = createOrgByTenant(tenant);// 生成org
		createOrgAccount(org);// 生成机构账户
		createTenantDicttype(tenant);// 生成 dicttenant 数据
		Role role = createRoleByTenant(tenant);// 生成角色
		createAdminUserByTenant(tenant, role, org);// 生成管理员
	}

	// 已发布租户修改租户角色权限数据
	public void operateTenantRole(Tenant tenant) {
		StringBuilder query = new StringBuilder(
				"select c from Role c where c.delStatus != ?2 and c.tenant.id = ?1 and c.code=?3 ");
		Role adminRole = (Role) this.em.createQuery(query.toString()).setParameter(1, tenant.getId())
				.setParameter(2, (short) 1).setParameter(3, "admin").getSingleResult();
		query.delete(0, query.length());
		query.append("select c from TenantPrivilege c where c.delStatus != ?2 and c.tenant.id = ?1");
		if (adminRole != null) {
			List<TenantPrivilege> privilegesT = this.em.createQuery(query.toString()).setParameter(1, tenant.getId())
					.setParameter(2, (short) 1).getResultList();
			List<Privilege> privileges = new ArrayList<>();
			for (TenantPrivilege data : privilegesT) {
				privileges.add(data.getPrivilege());
			}
			adminRole.setPrivileges(privileges);
			dslJpaService.setEntityClass(Role.class);
			adminRole = (Role) dslJpaService.update(adminRole);
		}
	}

	public DicttypeTenant getDicttypeTenantById(Long id) {
		StringBuilder query = new StringBuilder("select c from DicttypeTenant c where c.id = ?1 and c.delStatus!=?2 ");
		DicttypeTenant ct = (DicttypeTenant) this.em.createQuery(query.toString()).setParameter(1, id)
				.setParameter(2, (short) 1).getSingleResult();
		return ct;
	}

	public DicttypeTenant getDicttypeTenantByTypeGroup(String typename, String code) {
		StringBuilder query = new StringBuilder(
				"select c from DicttypeTenant c where c.typename = ?1 and c.delStatus!=?2 and c.typegroupTenant.typegroupcode=?3 and c.tenant.id=?4");
		List dataList = this.em.createQuery(query.toString()).setParameter(1, typename).setParameter(2, (short) 1)
				.setParameter(3, code).setParameter(4, ActionContextHolder.getContext().getTenantId()).getResultList();
		DicttypeTenant ct = null;
		if (dataList.size() > 0) {
			ct = (DicttypeTenant) dataList.get(0);
		}
		return ct;
	}

	public DicttypeTenant getDicttypeTenantByTypeGroupFilterId(String typename, Long groupId, Long id) {
		StringBuilder query = new StringBuilder(
				"select c from DicttypeTenant c where c.typename = ?1 and c.delStatus!=?2 and c.typegroupTenant.id=?3 and c.id!=?4 and c.tenant.id=?5 ");
		List dataList = this.em.createQuery(query.toString()).setParameter(1, typename).setParameter(2, (short) 1)
				.setParameter(3, groupId).setParameter(4, id)
				.setParameter(5, ActionContextHolder.getContext().getTenantId()).getResultList();
		DicttypeTenant ct = null;
		if (dataList.size() > 0) {
			ct = (DicttypeTenant) dataList.get(0);
		}
		return ct;
	}

	/**
	 * 获取tenant 通过 联系人电话
	 */
	public List<Tenant> getTenantByTel(String tel) {
		String query = "select c from Tenant c where c.delStatus != ?1 and c.linkManTel=?2";
		List dataList = this.em.createQuery(query).setParameter(1, (short) 1).setParameter(2, tel).getResultList();
		return dataList;
	}

	/**
	 * 获取所有已发布的租户
	 * 
	 * @author ytche
	 * @return
	 * @date 2017年6月5日 下午6:43:13
	 */
	public List<Tenant> findActiveTenant() {
		;
		String queryStr = "from Tenant t where t.delStatus != 1 and t.status = ?1";
		return this.em.createQuery(queryStr)
				.setParameter(1, this.dicttypeService.findByCode(CommonConstants.DICTTYPE.TENANT_STATUS_1.label()))
				.getResultList();
	}
}
